package com.elite.groovy.callback

import com.alibaba.fastjson.JSONObject
import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.IpAddressUtil
import com.elite.groovy.util.Util
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
 * @author UNIQLO
 *
 */

public class apiChatToken implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiChatToken.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();
        String outData = "";

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            outData = "{\"retCode\":\"-1\",\"retMsg\":\"API被非法IP调用-Request Not Allow!"+IpAddressUtil.getIpAddress(request)+"\",\"message\":\"非法IP调用\"}";
            log.warn(outData);
            return outData;
        }


        String getMethod = request.getMethod();
        log.debug("HTTP请求调用类型 getMethod:" + getMethod);
        if (getMethod != "POST") {
            outData = "{\"retCode\":\"-1\",\"retMsg\":\"HTTP请求调用类型错误，接口调用失败："+getMethod+"\",\"message\":\"调用类型错误\"}";
            log.error(outData);
            return outData;
        }

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("Call Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> mapParam = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("Call Parameter-" + key + ":" + value);
            mapParam.put(key, value);

        }

        // 获取调用数据
        String Syncpram = "";
        if (getMethod.equals("GET")) {
            Syncpram = request.getQueryString();
            log.info("接收调用GET参数信息：" + Syncpram);
        } else if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                Syncpram += line;
            }
            log.info("接收调用POST报文信息：" + System.getProperty("line.separator") + Syncpram);
        }

        try {
            // 解析请求报文-该接口模拟宏盛直接返回
            JSONObject callJson = JSONObject.parseObject(Syncpram);
            String apiKey = callJson.getString("apiKey");
            String timestamp = callJson.getString("timestamp");
            String sign = callJson.getString("sign");
            String loginId = callJson.getString("loginId");
            log.debug("解析请求参数-apiKey：" + apiKey + " timestamp:" + timestamp + " sign:" + sign + " loginId:" + loginId);

            outData = "{\"retCode\":\"1\",\"retMsg\":\"操作成功\",\"message\":{\"apiToken\":{\"createDate\":\""+startTime+"\",\"token\":\""+KHUtil.getRandomString(36)+"\",\"expires_in\":7200,\"user_id\":\"\",\"login_id\":\"\"}}}\n";

            log.debug("返回请求结果:" + outData);

        } catch (Exception e) {
            log.error(Util.getERRO(e));
            outData = e.toString();
        }
        return outData;

    }
}